import { createReducer } from './util';
import * as MachineAction from '../actions/machine';
import _ from 'lodash';

export const machineList = createReducer(on => {
  on(MachineAction.search);
  on(MachineAction.cleanMachineList);
  on(MachineAction.searchMachineByCompanyId);
  on(MachineAction.initialize)
    .completed((state, action) => {
      const machine = action.payload;
      const machines = state.list.map((om) => {
        if (om.id === machine.id) {
          return Object.assign({}, om, { status: 'NEW' });
        }
        return om;
      });
      return Object.assign({}, state, { list: machines });
    });

  on(MachineAction.provide)
    .completed((state, action) => {
      const machine = action.payload;
      const machines = state.list.map((om) => {
        if (om.id === machine.id) {
          return Object.assign({}, om, { status: 'INITIALIZING' });
        }
        return om;
      });
      return Object.assign({}, state, { list: machines });
    });

  on(MachineAction.remove)
    .completed((state, action) => {
      const machine = action.payload;
      const machines = state.list.filter((om) => {
        return om.id !== machine.id;
      });
      return Object.assign({}, state, { list: machines });
    });

  on(MachineAction.updateMachineStatus)
    .completed((state, action) => {
      if (_.isEmpty(state)) {
        return state;
      }
      const machines = state.list.map(machine => {
        if (machine.id !== action.payload.id) {
          return machine;
        }
        return Object.assign({}, machine, { status: action.payload.status });
      });
      return Object.assign({}, state, { list: machines });
    });
}, {});

export const machineSourceList = createReducer(on => {
  on(MachineAction.listAllMachineSources);
}, []);
export const companymMachineSourceList = createReducer(on => {
  on(MachineAction.listMachineSourcesByCompanyId);
}, []);
